<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

class Settings {
	/**
	 * Return current settings id
	 */
	public static function getCurrentId() {
		$current_id = 0;
		
		$result = Query::factory('select')
			->fields('id')
			->table('tbl_settings')
			->where("`status_id`=1")
			->orderBy('id', Query::ORDER_ASC)
			->limit(1)
			->execute()
			->row();
		
		if (!empty($result)) {
			$current_id = (int)$result['id'];
		}
		
		return $current_id;
	}

	/**
	 * Return settings info
	 */
	public static function getInfo($fields = '*') {
		$id = self::getCurrentId();
		return Query::factory('select')
			->table('tbl_settings')
			->fields($fields)
			->where("`id`=%d", $id)
			->limit(1)
			->execute()
			->row();
	}

	/**
	 * Return settings data
	 */
	public static function getData() {
		$id = self::getCurrentId();
		return new Data('settings.xml', 'tbl_settings_fields', 'settings_id', $id);
	}

	/**
	 * Insert settings
	 */
	public static function insert($data) {
		$query = Query::factory('insert')
			->table('tbl_settings')
			->data($data);
		
		$id = intval($query->execute()->getLastId());
		
		if ($id > 0) {
			Schema::saveFields('settings.xml', 'tbl_settings_fields', 'settings_id', $id, true);
		}

		return $id;
		
	}

	/**
	 * Update settings
	 */
	public static function update($data) {
		$id = self::getCurrentId();

		$query = Query::factory('update')
			->table('tbl_settings')
			->data($data)
			->where("id=%d", $id);

		$result = ($query->execute()->getAffectedRows() > 0);	
		
		if ($result) {
			Schema::saveFields('settings.xml', 'tbl_settings_fields', 'settings_id', $id);
		}
		
		return $result;
	}
}
